package com.freexiaoyu.freevideoplay;

import com.freexiaoyu.freevideoplay.utils.CommonUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpVideoStreamSaver {
    public static void saveVideoToMp4(String outputFilePath) {
        try {
            // 创建Socket连接

            ServerSocket serverSocket = new ServerSocket(22000);
            Socket clientSocket = serverSocket.accept(); // 这里应该在一个单独的线程中运行以避免阻塞UI线程
            InputStream inputStream = clientSocket.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);

            byte[] buffer = new byte[2048];
            int bytesRead;

            // 读取视频流并写入文件
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流和Socket
            fileOutputStream.close();
            inputStream.close();
            serverSocket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void saveFile(InputStream inputStream, String outputFilePath) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 读取视频流并写入文件
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流和Socket
            fileOutputStream.close();
            inputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void saveFile2(InputStream inputStream, String outputFilePath) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
            byte[] buffer = new byte[1024];
            int bytesRead;
            int inputLenght=inputStream.read(buffer);
            // 读取视频流并写入文件
            while ((bytesRead = inputLenght) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);


                //String videoHex= CommonUtil.bytesToHexString(buffer,false);
                //String currentFrameHex=videoHex.substring(0,4);
                //int currentFrame= Integer.parseInt(currentFrameHex, 16);
                //videoHex=videoHex.substring(4,(currentFrame*2));
                //videoHex=videoHex.substring(28,videoHex.length());
                //buffer=CommonUtil.hexStringToBytes(videoHex);
                //bytesRead = inputStream.read(buffer);
                //fileOutputStream.write(buffer, 0, bytesRead);
            }


            // 关闭流和Socket
            fileOutputStream.close();
            inputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
